package pre.lxm.demo.chart;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import pre.lxm.demo.chart.bean.RecordBean;

public class RecordChartView extends View {


    private Context mContext;
    private int mWidth, mHeight;
    private int itemHeight, itemWidth;
    private Paint mPaint;
    private TextPaint mTextPaint;


    private int leftPadding = 30;
    private int rightPadding = 30;
    private int topPadding = 20;
    private int bottomPadding = 20;

    private List<RecordBean> mRecordList = new ArrayList<>();


    private int fixNumber = 12;

    private int lineHeight = 6;
    String resultString[] = new String[]{"胜", "平", "负"};
    //轮次
    private int turnColor = Color.parseColor("#828282");
    private static final String turnString = "轮次";
    private int turnTextSize;

    public RecordChartView(Context context) {
        super(context, null);
//        mContext = context;
        init();
    }

    public RecordChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
//        mContext = context;
        init();
    }

    public RecordChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint = new TextPaint();
        initPaint();
        initTextPaint();
    }

    private void initPaint() {
        mPaint.setColor(Color.parseColor("#E1E1E1"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(lineHeight);
    }


    private void initTextPaint() {
        mTextPaint.setTextSize(40);
        mTextPaint.setStrokeWidth(6);
        mTextPaint.setColor(turnColor);
//        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);


//        setMeasuredDimension(mWidth, getMeasuredHeight());

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mWidth = getWidth();
        mHeight = getHeight();
        itemHeight = (mHeight - lineHeight * 2) / 4;
        itemWidth = (mWidth - leftPadding - rightPadding) / (fixNumber + 1);

        drawHorizonLine(canvas);
        drawLeftText(canvas);

        drawTurn(canvas, mRecordList);
    }

    //getMeasuredHeight()/2 + (fontMetrics.descent- fontMetrics.ascent)/2 - fontMetrics.descent
    //绘制字体
    private void drawLeftText(Canvas canvas) {

        Rect turnRect = new Rect();
        mTextPaint.getTextBounds(turnString, 0, turnString.length(), turnRect);
        mTextPaint.setTextSize(40);
        Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
        int baseline = itemHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;

//        canvas.drawText("轮次", (itemWidth + leftPadding - turnRect.width()) / 2, (lineHeight * 2 +
//                topPadding + bottomPadding + itemHeight - turnRect.height()) / 2, mTextPaint);
//        mTextPaint.setColor(Color.RED);
        canvas.drawText("轮次", (itemWidth + leftPadding - turnRect.width()) / 2, baseline, mTextPaint);
        //绘制胜平负
        canvas.save();

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.parseColor("#CECECE"));
        mPaint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{10, 10, 10, 10}, 1);

        mTextPaint.setColor(Color.parseColor("#313131"));
        canvas.translate(0, itemHeight + lineHeight * 2);
        for (int i = 0; i < 3; i++) {
            Rect mRect = new Rect();
            mTextPaint.getTextBounds(resultString[i], 0, 1, mRect);
            canvas.drawText(resultString[i], (itemWidth + leftPadding - mRect.width()) / 2,
                    (itemHeight - mRect.height()) / 2, mTextPaint);

            Path path = new Path();
            mPaint.setPathEffect(pathEffect);
            path.moveTo(itemWidth + leftPadding * 2, (itemHeight - mRect.height()) / 2 - lineHeight * 2);
            path.lineTo(mWidth - rightPadding, (itemHeight - mRect.height()) / 2 - lineHeight * 2);
            canvas.drawPath(path, mPaint);
            canvas.translate(0, itemHeight);
        }
        canvas.restore();

    }

    public void refreshData(List<RecordBean> recordList) {
        mRecordList.clear();
        mRecordList.addAll(recordList);
        invalidate();
    }

    private void drawTurn(Canvas canvas, List<RecordBean> recordList) {
        mTextPaint.setColor(Color.parseColor("#424242"));
        canvas.save();
        canvas.translate(itemWidth + leftPadding * 2, 0);
        int size = recordList.size();
        for (int i = 0; i < size; i++) {
            RecordBean itemRecord = recordList.get(i);
            Rect mRect = new Rect();
            mTextPaint.getTextBounds(itemRecord.getTurn(), 0, itemRecord.getTurn().length(), mRect);
            Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
            int baseline = itemHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
//            canvas.drawText(itemRecord.getTurn(), (itemWidth - mRect.width()) / 2, (lineHeight * 2 +
//                    topPadding + bottomPadding + itemHeight - mRect.height()) / 2, mTextPaint);
            canvas.drawText(itemRecord.getTurn(), (itemWidth - mRect.width()) / 2, baseline, mTextPaint);
            canvas.translate(itemWidth, 0);
        }
        canvas.restore();

    }

    private void drawHorizonLine(Canvas canvas) {
        mPaint.setStrokeWidth(lineHeight);
        canvas.drawLine(0, lineHeight, mWidth, lineHeight, mPaint);
        mPaint.setStrokeWidth(lineHeight);
        canvas.drawLine(0, itemHeight - lineHeight, mWidth, itemHeight - lineHeight, mPaint);

    }

//    private int lastX;
//    private int lastY;

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        //获取到手指处的横坐标和纵坐标
//        int x = (int) event.getX();
//        int y = (int) event.getY();
//
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                lastX = x;
////                lastY = y;
//                break;
//
//            case MotionEvent.ACTION_MOVE:
//                //计算移动的距离
//                int offsetX = x - lastX;
////                int offsetY = y - lastY;
//                //调用layout方法来重新放置它的位置
//                layout(getLeft() + offsetX, getTop(),
//                        getRight() + offsetX, getBottom());
//                break;
//        }
//        return true;
//    }

//    @Override
//    public void layout(@Px int l, @Px int t, @Px int r, @Px int b) {
//        super.layout(l, t, r, b);
//        Log.e("TAG", "---l:" + l + "\tt:" + t + "\tr:" + r + "\tb:" + b);
//
//    }




    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}
